package com.ypinkj.app.utils;

import java.time.LocalDate;
import java.time.Period;
import java.time.format.DateTimeFormatter;

/**
 * @author LF
 * @date 2020/10/19 - 14:45
 */
public class DateUtils {

    /**
     * 计算2个日期之间相差的  相差多少年月日
     * 比如：2011-02-02 到  2017-03-02 相差 6年，1个月，0天
     * @param fromDate YYYY-MM-DD
     * @param toDate YYYY-MM-DD
     * @return 年,月,日 例如 1,1,1
     */
    public static String dayComparePrecise(String fromDate, String toDate){
        if(precise(fromDate,toDate)) {
            Period period = Period.between(LocalDate.parse(fromDate), LocalDate.parse(toDate));
            StringBuffer sb = new StringBuffer();
            int years = period.getYears();
            int months = period.getMonths();
            //System.out.println(years+"==============="+months);
            if (years == 0 && months == 0) {
                return "未知";
            }
            if (years != 0) {
                sb.append(period.getYears()).append("年");
            }
            if (period.getMonths() != 0) {
                sb.append(period.getMonths());
                sb.append("个月");
            }
            //.append(period.getDays());
            return sb.toString();
        }
        return "-1";
    }

    //获取当前日期
    public static String formatDate(){
        LocalDate date = LocalDate.now(); // get the current date
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        //System.out.println(date.format(formatter));
        return date.format(formatter);
    }

    //比对日期
    public static boolean precise(String fromDate, String toDate){
        String oldDate = fromDate.replace("-", "");
        String newDate = toDate.replace("-", "");
        int i = Integer.parseInt(oldDate);
        int i1 = Integer.parseInt(newDate);
        //System.out.println(i+"------------"+i1);
        return i<i1 ? true : false;
    }

    public static void main(String[] args) {
        formatDate();
        System.out.println(dayComparePrecise("2016-06-15", "2020-07-20"));
        System.out.println(precise("2016-06-15", "2020-06-20"));
    }
}
